#include "dynamic_string_queue.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 内部字符串复制函数
static char* queue_strdup(const char *s) {
    if (s == NULL) return NULL;
    
    size_t len = strlen(s) + 1;
    char *new_str = malloc(len);
    if (new_str == NULL) return NULL;
    
    strcpy(new_str, s);
    return new_str;
}

// 创建新队列节点
static QueueNode* createNode(const char *str) {
    QueueNode *node = malloc(sizeof(QueueNode));
    if (node == NULL) return NULL;
    
    node->data = queue_strdup(str);
    if (node->data == NULL) {
        free(node);
        return NULL;
    }
    
    node->next = NULL;
    return node;
}

DynamicStringQueue* createQueue(int capacity) {
    DynamicStringQueue *q = malloc(sizeof(DynamicStringQueue));
    if (q == NULL) return NULL;
    
    q->front = q->rear = NULL;
    q->size = 0;
    q->capacity = (capacity > 0) ? capacity : 0; // 0表示无限容量
    return q;
}

bool isEmpty(DynamicStringQueue *q) {
    return q == NULL || q->size == 0;
}

bool isFull(DynamicStringQueue *q) {
    return q != NULL && q->capacity > 0 && q->size >= q->capacity;
}

bool enqueue(DynamicStringQueue *q, const char *str) {
    if (q == NULL || str == NULL) return false;
    if (isFull(q)) {
        fprintf(stderr, "Queue is full\n");
        return false;
    }
    
    QueueNode *node = createNode(str);
    if (node == NULL) return false;
    
    if (isEmpty(q)) {
        q->front = q->rear = node;
    } else {
        q->rear->next = node;
        q->rear = node;
    }
    
    q->size++;
    return true;
}

bool dequeue(DynamicStringQueue *q, char **str) {
    if (q == NULL || str == NULL || isEmpty(q)) {
        return false;
    }
    
    QueueNode *temp = q->front;
    *str = temp->data; // 转移字符串所有权给调用者
    
    q->front = q->front->next;
    if (q->front == NULL) {
        q->rear = NULL;
    }
    
    q->size--;
    free(temp); // 只释放节点，不释放字符串
    return true;
}

bool peek(DynamicStringQueue *q, char **str) {
    if (q == NULL || str == NULL || isEmpty(q)) {
        return false;
    }
    
    *str = q->front->data; // 不转移所有权
    return true;
}

void clearQueue(DynamicStringQueue *q) {
    if (q == NULL) return;
    
    char *str;
    while (dequeue(q, &str)) {
        free(str); // 释放字符串内存
    }
}

void destroyQueue(DynamicStringQueue *q) {
    if (q == NULL) return;
    
    clearQueue(q);
    free(q);
}

void printQueue(DynamicStringQueue *q) {
    if (q == NULL || isEmpty(q)) {
        printf("Queue is empty\n");
        return;
    }
    
    printf("Queue (size: %d/%d):\n", q->size, q->capacity);
    QueueNode *current = q->front;
    int index = 0;
    while (current != NULL) {
        printf("[%d] %s\n", index++, current->data);
        current = current->next;
    }
}